/*
 *  File: SerlvetContextCache.java 
 *
 *  @author jeffliu
 *  @date Jun 24, 2011
 *  @version 
 */
package com.yulookbook.web.util;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Logger;

import com.yulookbook.util.Cache;
import com.yulookbook.util.Log;

public class SerlvetContextCache implements Cache {
	
	private final static Logger LOGGER = Log.getLogger(SerlvetContextCache.class);
	
	static SerlvetContextCache instance = null;
	
	public static SerlvetContextCache getInstance(){
		if(instance == null){
			synchronized(SerlvetContextCache.class){
				if(instance == null)
					instance = new SerlvetContextCache();
			}
		}
		return instance;
	}
	
	private int size = Cache.DEFAULT_MAX_SIZE;
	private HashMap<String,String> map;
	private LinkedList<String> keys;
	
	private SerlvetContextCache(){
		super();
		init();
	}
	
	private void init(){
		map = new HashMap<String,String>(size);
		keys = new LinkedList<String>();
	}
	
	public void clear() {
		map.clear();
		keys.clear();
	}

	public boolean containKey(Object key) {
		return keys.contains(key);
	}

	public Object get(Object key) {
		if(containKey(key)){
			LOGGER.info("key hit:"+key);
			return map.get(key);
		}
		else{
			LOGGER.info("key miss:"+key);
			return null;
		}
	}

	public void put(Object key, Object value) {
		if(!containKey(key)){
			if(keys.size()>= this.size){
				String rkey = keys.poll();
				LOGGER.info("cache pool is full remove key:"+key);
				map.remove(rkey);
			}
			keys.offer((String) key);
			LOGGER.info("put key:"+key);
			map.put((String)key, (String)value);
		}
	}

	public void remove(Object key) {
		if(containKey(key)){
			map.remove(key);
			keys.remove(key);
		}	
	}

	public void setMaxSize(int size) {
		this.size = size;
		init();
	}

}
